<?php

namespace app\common\service;

use app\common\model\Transaction;
use randy\tools\units\ExtendQueryHelper;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class TransactionService extends BaseService
{
    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function getTransactionList(ExtendQueryHelper $extendQueryHelper, $data)
    {
        $query = Transaction::build()
                            ->withJoin('user')
                            ->where($extendQueryHelper->where)
                            ->order($extendQueryHelper->sort, $extendQueryHelper->order);
        return $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
    }

    public function getTransactionItem($id)
    {
        return Transaction::build()
                          ->findOrFail($id);
    }

    public function delTransactionItem($id)
    {
        $info = Transaction::find($id);
        return $info->delete();
    }

    public function setTransactionItem($id, $data)
    {
        $info = Transaction::find($id);
        $info->save($data);
        return $info;
    }


    public function addTransactionItem($data)
    {
        $model = new Transaction();
        $model->save($data);
        return $model;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getUseFinishTask($user_id) : \think\Collection|array
    {
        $date = date('Y-m-d');
        return Transaction::build()
                          ->field(['source_type', 'sum(amount) amount', 'user_id'])
                          ->where('user_id', $user_id)
                          ->where('create_date', $date)
                          ->group('source_type')
                          ->select();
    }

    public function today($user_id)
    {
        $inc = Transaction::build()
                          ->where('user_id', $user_id)
                          ->where('type', 1)
                          ->where('create_date', date('Y-m-d'))
                          ->sum('amount');

        return ['points_num' => $inc];
    }


}
